import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import fs from 'node:fs'
import path from 'node:path'

global.windows = new Map()

interface WindowOptions {
  options: Electron.BrowserWindowConstructorOptions
  name: string
  router: string
}

const createWindow = (option: WindowOptions) => {
  if (global.windows.has(option.name)) {
    global.windows.get(option.name).show()
    global.windows.get(option.name).focus()
    return global.windows.get(option.name)
  }
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    show: false,
    titleBarStyle: 'hidden',
    titleBarOverlay: true,
    autoHideMenuBar: true,
    minimizable: false,
    maximizable: false,
    // 保留系统窗口控制按钮
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    },
    ...option.options
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + option.router || '')
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: option.router || ''
    })
  }

  mainWindow.on('closed', () => {
    global.windows.delete(option.name)
  })

  mainWindow.setMinimizable(false)
  mainWindow.setFullScreenable(false)
  // mainWindow.setWindowButtonVisibility(false)
  global.windows.set(option.name, mainWindow)
  return mainWindow
}

const createIPCEvent = (): void => {
  // 关闭窗口
  ipcMain.on('close-window', (_, windowName) => {
    const window = global.windows.get(windowName)
    if (window) {
      window.close()
    }
  })

  // 任务清单事件

  // 获取任务清单数据
  ipcMain.handle('getTodoDataList', () => {
    if (!fs.existsSync(path.join(app.getPath('userData'), 'todoList.json'))) {
      fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), '[]')
    }
    // 将文件内容读取并返回
    return JSON.parse(fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8'))
  })

  // 添加任务清单数据
  ipcMain.on('addTodoData', (_, todoItem) => {
    // 将todoItem添加到文件内容中
    const todoList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
    )
    todoList.push(todoItem)
    fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), JSON.stringify(todoList))
  })

  // 删除任务清单数据
  ipcMain.on('deleteTodoData', (_, id) => {
    // 将todoItem添加到文件内容中
    const todoList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
    )
    const trashList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'trash.json'), 'utf8')
    )
    const deleteItem = todoList.find((item) => item.id === id)
    deleteItem.isDelete = true
    todoList.splice(todoList.indexOf(deleteItem), 1)
    trashList.push(deleteItem)
    fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), JSON.stringify(todoList))
    fs.writeFileSync(path.join(app.getPath('userData'), 'trash.json'), JSON.stringify(trashList))
  })

  // 更新任务清单数据
  ipcMain.on('updateTodoData', (_, todoItem) => {
    const todoList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
    )
    const oldTodoItem = todoList.find((item) => item.id === todoItem.id)
    if (oldTodoItem) {
      Object.assign(oldTodoItem, todoItem)
    }
    fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), JSON.stringify(todoList))
  })

  // 获取任务清单导航数据
  ipcMain.handle('getTodoNavList', () => {
    if (!fs.existsSync(path.join(app.getPath('userData'), 'todoNavList.json'))) {
      fs.writeFileSync(path.join(app.getPath('userData'), 'todoNavList.json'), '[]')
    }
    return JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoNavList.json'), 'utf8')
    )
  })

  // 添加任务清单导航数据
  ipcMain.on('addTodoNavData', (_, todoNavItem) => {
    const todoNavList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoNavList.json'), 'utf8')
    )
    if (todoNavList.findIndex((item) => item.name === todoNavItem.name) !== -1) {
      return global.windows.get('addTodoNav').webContents.send('error', '清单名称已存在')
    }
    todoNavList.push(todoNavItem)
    fs.writeFileSync(
      path.join(app.getPath('userData'), 'todoNavList.json'),
      JSON.stringify(todoNavList)
    )
    global.windows.get('main').webContents.send('todoNavAdd', todoNavItem)
    global.windows.get('addTodoNav').close()
  })

  ipcMain.on('deleteTodoNavData', (_, id) => {
    const todoNavList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoNavList.json'), 'utf8')
    )
    const index = todoNavList.findIndex((item) => item.id === id)
    const navItem = todoNavList[index]
    todoNavList.splice(index, 1)
    fs.writeFileSync(
      path.join(app.getPath('userData'), 'todoNavList.json'),
      JSON.stringify(todoNavList)
    )

    let todoList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
    )
    todoList = todoList.filter((item) => item.group !== navItem.name)
    fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), JSON.stringify(todoList))
  })

  // 更新任务清单导航数据
  ipcMain.on('updateTodoNavData', (_, todoNavItem) => {
    const todoNavList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoNavList.json'), 'utf8')
    )
    const oldTodoItem = todoNavList.find((item) => item.id === todoNavItem.id)
    if (!oldTodoItem) {
      return global.windows.get('addTodoNav').webContents.send('error', '清单不存在')
    }

    if (
      todoNavList.findIndex(
        (item) => item.name === todoNavItem.name && item.id !== todoNavItem.id
      ) !== -1
    ) {
      return global.windows.get('addTodoNav').webContents.send('error', '清单名称已存在')
    }

    const todoList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
    )
    todoList.forEach((item) => {
      if (item.group === oldTodoItem.name) {
        item.group = todoNavItem.name
      }
    })
    fs.writeFileSync(path.join(app.getPath('userData'), 'todoList.json'), JSON.stringify(todoList))
    if (oldTodoItem) {
      Object.assign(oldTodoItem, todoNavItem)
    }
    fs.writeFileSync(
      path.join(app.getPath('userData'), 'todoNavList.json'),
      JSON.stringify(todoNavList)
    )
    global.windows.get('main').webContents.send('todoNavUpdate', todoNavItem)
    global.windows.get('addTodoNav').close()
  })

  ipcMain.on('getEditTodoNavData', () => {
    global.windows.get('main').webContents.send('getEditTodoNavData')
  })

  ipcMain.on('sendTodoNavData', (_, todoNavItem) => {
    global.windows.get('addTodoNav').webContents.send('sendTodoNavData', todoNavItem)
  })

  ipcMain.handle('getTrashData', () => {
    if (!fs.existsSync(path.join(app.getPath('userData'), 'trash.json'))) {
      fs.writeFileSync(path.join(app.getPath('userData'), 'trash.json'), '[]')
    }
    return JSON.parse(fs.readFileSync(path.join(app.getPath('userData'), 'trash.json'), 'utf8'))
  })

  ipcMain.on('deleteTrashData', (_, id) => {
    const trashList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'trash.json'), 'utf8')
    )
    trashList.splice(
      trashList.findIndex((item) => item.id === id),
      1
    )
    fs.writeFileSync(path.join(app.getPath('userData'), 'trash.json'), JSON.stringify(trashList))
  })

  ipcMain.on('restoreTrashData', (_, id) => {
    const trashList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'trash.json'), 'utf8')
    )
    const restoreItem = trashList.find((item) => item.id === id)
    restoreItem.isDelete = false
    if (restoreItem) {
      const todoList = JSON.parse(
        fs.readFileSync(path.join(app.getPath('userData'), 'todoList.json'), 'utf8')
      )
      todoList.push(restoreItem)
      trashList.splice(trashList.indexOf(restoreItem), 1)
      fs.writeFileSync(
        path.join(app.getPath('userData'), 'todoList.json'),
        JSON.stringify(todoList)
      )
      fs.writeFileSync(path.join(app.getPath('userData'), 'trash.json'), JSON.stringify(trashList))
    }
  })

  ipcMain.handle('getHabitDataList', () => {
    if (!fs.existsSync(path.join(app.getPath('userData'), 'habit.json'))) {
      fs.writeFileSync(path.join(app.getPath('userData'), 'habit.json'), '[]')
    }
    return JSON.parse(fs.readFileSync(path.join(app.getPath('userData'), 'habit.json'), 'utf8'))
  })

  ipcMain.on('addHabitData', (_, habitItem) => {
    const habitList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'habit.json'), 'utf8')
    )
    if (habitList.findIndex((item) => item.name === habitItem.name) !== -1) {
      return global.windows.get('addHabit').webContents.send('error', '名称已存在')
    }
    habitList.push(habitItem)
    fs.writeFileSync(path.join(app.getPath('userData'), 'habit.json'), JSON.stringify(habitList))
    // global.windows.get('main').webContents.send('addHabitData', habitItem)
    // global.windows.get('addHabit').close()
  })

  // 删除任务清单数据
  ipcMain.on('deleteHabitData', (_, id) => {
    // 将todoItem添加到文件内容中
    const habitList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'habit.json'), 'utf8')
    )
    habitList.splice(
      habitList.findIndex((item) => item.id === id),
      1
    )
    fs.writeFileSync(path.join(app.getPath('userData'), 'habit.json'), JSON.stringify(habitList))
  })

  ipcMain.on('updateHabitData', (_, habitItem) => {
    const habitList = JSON.parse(
      fs.readFileSync(path.join(app.getPath('userData'), 'habit.json'), 'utf8')
    )
    const oldHabitItem = habitList.find((item) => item.id === habitItem.id)
    if (oldHabitItem) {
      Object.assign(oldHabitItem, habitItem)
    }
    fs.writeFileSync(path.join(app.getPath('userData'), 'habit.json'), JSON.stringify(habitList))
  })

  // 创建任务清单导航窗口
  ipcMain.on('addTodoNav', (_) => {
    return createWindow({
      name: 'addTodoNav',
      router: '#/addTodoNav',
      options: {
        width: 360,
        height: 420,
        center: true, // 窗口居中
        title: '添加任务清单'
      }
    })
  })

  ipcMain.on('openSetting', () => {
    return createWindow({
      name: 'setting',
      router: '#/setting',
      options: {
        width: 800,
        height: 700,
        center: true, // 窗口居中
        title: '设置',
        frame: false,
        autoHideMenuBar: true
      }
    })
  })

  ipcMain.on('themeToggle', (_, theme) => {
    global.windows.get('main').webContents.send('themeToggle', theme)
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.xingzhi')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createIPCEvent()

  createWindow({
    name: 'main',
    router: '',
    options: {
      width: 1280,
      height: 800,
      show: false,
      titleBarStyle: 'hidden',
      titleBarOverlay: true,
      autoHideMenuBar: true,
      ...(process.platform === 'linux' ? { icon } : {}),
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    }
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow({
        name: 'main',
        router: '',
        options: {}
      })
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
